from sanic import Blueprint
from sanic.response import json
import jwt
import datetime
from jwt import exceptions

bp = Blueprint(__name__, url_prefix='/token')

@bp.route("/")
async def root(request):
    return json(set_token())

@bp.get("/quit")
async def quit(request):
    return json({"msg": "quit"})

def set_token():

    dic = {
        'exp': datetime.datetime.now() + datetime.timedelta(days=1),  # 过期时间
        'iat': datetime.datetime.now(),  # 开始时间
        'iss': 'lianzong',  # 签名
        'data': {  # 内容，一般存放该用户id和开始时间
            'a': 1,
            'b': 2,
        },
    }

    # 加密
    token = jwt.encode(dic, 'secret', algorithm='HS256')  # 加密生成字符串

    try:
        # 解密，校验签名
        info = jwt.decode(token, 'secret', issuer='lianzong', algorithms=['HS256'])
        print(info)
    except exceptions.ExpiredSignatureError:
        print('token已失效')
    except jwt.DecodeError:
        print('token认证失败')
    except jwt.InvalidTokenError:
        print('非法的token')

    return {'token': token}